const got = require('got')
const iconv = require('iconv-lite')

async function testSearch() {
  console.log('开始测试股票搜索API...')
  try {
    console.log('发送请求到: https://suggest3.sinajs.cn/suggest/key=600')
    const response = await got('https://suggest3.sinajs.cn/suggest/key=600', {
      headers: {
        'Referer': 'https://finance.sina.com.cn',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
      },
      timeout: 5000,
      retry: 1,
      responseType: 'buffer'  // 获取原始buffer以便转换编码
    })
    
    // 将GBK编码的Buffer转换为UTF-8字符串
    const body = iconv.decode(response.body, 'GBK')
    
    console.log('收到响应:')
    console.log('状态码:', response.statusCode)
    console.log('响应头:', response.headers)
    console.log('响应体(UTF-8):', body)

    // 解析数据
    console.log('\n开始解析数据...')
    const data = body.replace('var suggestvalue="', '').replace('";', '')
    console.log('清理后的数据:', data)
    
    const stocks = data.split(';')
      .filter(item => item && item.trim())
      .map(item => {
        const parts = item.split(',')
        if (parts.length < 3) return null
        return {
          market: parts[0],
          code: parts[2],
          name: parts[4]
        }
      })
      .filter(item => item !== null)
    console.log('\n解析后的股票数据:', stocks)
  } catch (error) {
    console.error('发生错误:')
    console.error('错误名称:', error.name)
    console.error('错误信息:', error.message)
    if (error.response) {
      console.error('错误响应状态码:', error.response.statusCode)
      console.error('错误响应头:', error.response.headers)
      console.error('错误响应体:', error.response.body)
    }
    console.error('错误堆栈:', error.stack)
  }
}

console.log('启动测试...')
testSearch() 